package com.google.code.porntube.snap.task;

import java.io.IOException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.memcache.ErrorHandlers;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.code.porntube.snap.analyzer.Rss;
import com.google.code.porntube.snap.core.io.Store;
import com.google.code.porntube.snap.counter.SnapCounter;
import com.google.code.porntube.snap.result.Clip;

public final class SnapTask extends HttpServlet {

	private static final long serialVersionUID = -6272622566777530839L;

	private static Logger log = Logger.getLogger(SnapTask.class.getName());

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String catalog = request.getParameter("catalog");
		log.log(Level.INFO, "SNAP TASK", catalog);
		LinkedList<Clip> clips = Rss.analyze(catalog);
		MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
		syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
		for (Clip clip : clips) {
			Object value = syncCache.get(clip.getThumbnail());
			if (value == null) {
				syncCache.put(clip.getThumbnail(), clip.getUpdate());
				Store.push(clip);
				SnapCounter.add(catalog);
			}
		}
	}
}